package com.zhixing.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * <p> spring 上下文工具类 </p>
 *
 * @author zhixing
 */
public class SpringContextUtils implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (SpringContextUtils.applicationContext == null) {
            SpringContextUtils.applicationContext = applicationContext;
        }
    }

    /** 获取 applicationContext **/
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /** 通过name获取Bean **/
    public static <T> T getBean(String name) {
        if (applicationContext == null) {
            return null;
        }
        return (T) getApplicationContext().getBean(name);
    }

    /** 通过class获取Bean **/
    public static <T> T getBean(Class<T> clazz) {
        if (applicationContext == null) {
            return null;
        }
        return getApplicationContext().getBean(clazz);
    }

    /** 通过name,以及clazz返回指定的Bean **/
    public static <T> T getBean(String name, Class<T> clazz) {
        if (applicationContext == null) {
            return null;
        }
        return getApplicationContext().getBean(name, clazz);
    }

}
